package com.winshare.saleAssistant.exception.advice;

import com.winshare.saleAssistant.exception.BusinessException;
import com.winshare.saleAssistant.util.LogicResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = BusinessException.class)
    public LogicResponse<String>  exception(BusinessException e) {
        String message = e.getMessage();
        if (logger.isErrorEnabled()) {
            logger.error("本地业务异常：{}", message);
        }
        if (StringUtils.isEmpty(message)) {
            return LogicResponse.failure().build();
        }
        return LogicResponse.failure(message).build();
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public LogicResponse<String>  exception(HttpServletRequest request, MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> String.format("%s:%s", fieldError.getField(), fieldError.getDefaultMessage()))
                .collect(Collectors.joining(","));
        if (logger.isErrorEnabled()) {
            logger.error("接口：{}，参数异常：{}", request.getRequestURL(), message);
        }
        if (StringUtils.isEmpty(message)) {
            return LogicResponse.paramError().build();
        }
        return LogicResponse.paramError(message).build();
    }
}
